//
//  PhotosListViewModel.swift
//  Photos
//
//  Created by wangqi on 2021/10/20.
//

import Foundation
class PhotosListViewModel {
    var pageSize: Int = 10
    var pageIndex: Int = 1
    var haveNextPage: Bool {
        let result = datas.count > displayDatas.count
        return result
    }
    var displayDatas = [Photo]()
    var datas = [Photo]()
}
extension PhotosListViewModel {
    func refresh(_ callback:RequestCallback? = nil) -> () {
        Api.photos().onFinished {[weak self] response in
            guard let data = response.data,
                  let items = data["items"] as? [[String: Any]] else {
                callback?(.system_error(), nil)
                return
            }
            let list = Photo.setupWithListDatas(items)
            self?.datas = list
            if let subarray = self?.getDisplayDatas(at: 1),
               subarray.count > 0 {
                self?.pageIndex = 1
                self?.displayDatas = subarray
            }
            callback?(.no_error(), nil)
        }
    }
    func loadMore(_ callback:RequestCallback? = nil) -> () {
        let subarray = getDisplayDatas(at: pageIndex + 1)
        displayDatas.append(contentsOf: subarray)
        if subarray.count > 0 {
            pageIndex += 1
        }
        callback?(.no_error(), nil)
    }
}
private extension PhotosListViewModel {
    func getDisplayDatas(at index: Int) -> [Photo] {
        let count = (index - 1) * pageSize
        let fromIndex = index > 1 ? count - 1 : count
        let result = datas.subarray(from: fromIndex, length: pageSize)
        return result
    }
}
